#include "Subsystems/BlockBehaviors/SubsystemBulletBlockBehavior.h"
#include "GameRandom.hpp"
#include "Subsystems/SubsystemTerrain.h"
#include "Subsystems/SubsystemExplosions.h"
#include "Managers/BlocksManager.h"
#include "Log.h"
#include "Blocks/AirBlock.h"
#include "Blocks/BulletBlock.h"
#include "GameSingleton.h"

namespace PocketSurvival
{

    // 子弹打击到后会引发一点小爆炸，这个是用于引爆炸药桶的
        
    bool SubsystemBulletBlockBehavior::onHitAsProjectile(std::shared_ptr<CellFace> cellFace, ComponentBody *componentBody, WorldItem *worldItem)
    {
        BulletType bulletType = BulletBlock::GetBulletType(Terrain::ExtractData(worldItem->value));
        bool result = true;
        if (cellFace != nullptr)
        {
            int32_t cellValue = m_terrain->getCellValue(cellFace->point);
            int32_t num = Terrain::ExtractContents(cellValue);
            Block *obj = GameSingleton::blocksManager->blocks[num];
            if (worldItem->velocity.length() > 30.0f)
            {
                Point3 &point = cellFace->point;
                m_explosions->tryExplodeBlock(point.posX, point.posY, point.posZ, cellValue);
            }
            if (obj->Density >= 1.5f && worldItem->velocity.length() > 30.0f)
            {
                float num2 = 1.0f;
                float minDistance = 8.0f;
                if (bulletType == BulletType::BuckshotBall)
                {
                    num2 = 0.25f;
                    minDistance = 4.0f;
                }
                if (GameSingleton::gameRandom->getFloat(0.0f, 1.0f) < num2)
                {
                    result = false;
                }
            }
        }
        return result;
    }

    void SubsystemBulletBlockBehavior::load(const nlohmann::json &json)
    {
        m_explosions = GameSingleton::singletonPtr->getSingleton<SubsystemExplosions>();
        m_terrain = GameSingleton::singletonPtr->getSingleton<SubsystemTerrain>();
    }

    static const std::string subsystemName = "BulletBlockBehavior";
    const std::string &SubsystemBulletBlockBehavior::getName() const
    {
        return subsystemName;
    }
}
